<?php

class TeacherController extends ControllerBase {

    public function indexAction() {
        
    }

    public function testAction() {
        $identity = $this->auth->getIdentity();
        $exercises = Exercises::findByCreatedBy($identity['id']);
        $this->view->exercises = $exercises;
    }

    public function createTestAction() {
        $identity = $this->auth->getIdentity();
        if ($identity) {
            if ($this->request->isPost()) {

                $name = $this->request->getPost('name');
                $description = $this->request->getPost('description');
                $timeFrom = $this->request->getPost('startTime');
                $timeTo = $this->request->getPost('endTime');

                $params = $this->request->getPost('part');
                $questionsList = ExercisesLibrary::generateTest($params);

                $exercise = new Exercises();
                $exercise->assign(array(
                    'name' => $name,
                    'description' => $description,
                    'createdBy' => $identity['id'],
                    'createdTime' => strtotime(date('Y-m-d H:i:s')),
                    'startTime' => $timeFrom ? strtotime($timeFrom) : null,
                    'endTime' => $timeTo ? strtotime($timeTo) : null,
                    'questions' => implode(',', $questionsList),
                ));
                if ($exercise->save()) {
                    $this->response->redirect('teacher/test');
                } else {
                    print_r($exercise->getMessages());
                    die();
                }
            }
        }
    }

    public function generateTestAction($id) {
        $identity = $this->auth->getIdentity();
        if ($id) {
            $userExercise = Tests::findFirstByExercise($id);
            if (!$userExercise) {
                $exercise = Exercises::findFirstById($id);
                if ($exercise) {
                    $test = new Tests();
                    $test->assign(array(
                        'exercise' => $exercise->id,
                        'user' => $identity['id'],
                        'result' => 0,
                        'updatedTime' => strtotime(date('Y-m-d H:i:s')),
                    ));
                    if ($test->save()) {
                        $questions = explode(',', $exercise->questions);
                        foreach ($questions as $key => $value) {
                            $question = Questions::findFirstById($value);
                            if ($question) {
                                $testDetail = new TestDetails();
                                $testDetail->assign(array(
                                    'test' => $test->id,
                                    'question' => $question->id,
                                    'correct' => $question->correct,
                                    'audio' => $question->audio,
                                    'document' => $question->document,
                                    'image' => $question->image,
                                    'position' => $key + 1,
                                    'part' => $question->part,
                                ));
                                if (!$testDetail->save()) {
                                    print_r($testDetail->getMessages());
                                }
                            }
                        }
                        $this->response->redirect('teacher/do/' . $test->id);
                    } else {
                        print_r($test->getMessages());
                    }
                }
            } else {
                $this->response->redirect('teacher/do/' . $userExercise->id);
            }
        }
    }

    public function getQuestionsAction($id, $position = 1) {
        $questions = array();
        if ($id) {
            $testDetail = TestDetails::findFirst("test='$id' AND position='$position'");

            $question = Questions::findFirstById($testDetail->question);

            if ($question->part == 3 || $question->part == 4) {
                $testDetails = TestDetails::find(array(
                            "test='$id' AND audio='$question->audio'",
                            'sort' => 'position'
                ));
                foreach ($testDetails as $key => $detail) {
                    $qts = Questions::findFirstById($detail->question);
                    if ($qts) {
                        $qt = $qts->toArray();
                        $qt['testPosition'] = $detail->position;
                        $qt['answer'] = $detail->answer;
                        $questions[] = $qt;
                    }
                    if ($key == 0) {
                        $min = $detail->position;
                    }
                    if ($key == count($testDetails) - 1) {
                        $max = $detail->position;
                    }
                }
            } else if ($question->part == 6 || $question->part == 7) {
                $testDetails = TestDetails::find(array(
                            "test='$id' AND document='$question->document'",
                            'sort' => 'position'
                ));
                foreach ($testDetails as $detail) {
                    $qts = Questions::findFirstById($detail->question);
                    if ($qts) {
                        if ($testDetail->part == 6) {
                            $reference->content = str_replace("($qts->position)..........", "($detail->position)..........", $reference->content);
                        }
                        $qt = $qts->toArray();
                        $qt['testPosition'] = $detail->position;
                        $qt['answer'] = $detail->answer;
                        $questions[] = $qt;
                    }
                    if ($key == 0) {
                        $min = $detail->position;
                    }
                    if ($key == count($testDetails) - 1) {
                        $max = $detail->position;
                    }
                }
            } else {
                $qt = $question->toArray();
                $qt['testPosition'] = $testDetail->position;
                $qt['answer'] = $testDetail->answer;
                $questions[] = $qt;
                $min = $testDetail->position;
                $max = $testDetail->position;
            }

            $result = array(
                'questions' => $questions,
                'audio' => Audios::findFirstById($question->audio),
                'document' => Documents::findFirstById($question->document),
                'image' => Images::findFirstById($question->image),
                'next' => $max + 1,
                'pre' => $min - 1,
            );

            $this->view->disable();
            $this->response->setStatusCode(200, "OK");
            $this->response->setJsonContent($result);
            $this->response->send();
        }
    }

    public function doAction($id) {
        $test = Tests::findFirstById($id);
        if ($test) {
            $exercise = Exercises::findFirstById($test->exercise);
            if ($exercise) {
                if ($exercise->startTime && !(strtotime(date('Y-m-d H:i:s') < (int) $exercise->startTime) || strtotime(date('Y-m-d H:i:s') > (int) $exercise->endTime))) {
                    echo 'Out of time';
                } else {
                    $this->view->exercise = $exercise;
                    $this->view->room = $test->exercise;
                    $this->view->id = $id;
                    $this->view->current = 1;
                }
            }
        } else {
            $this->response->redirect('teacher/test');
        }
    }

    public function testResultAction($id) {
        $exercise = Exercises::findFirstById($id);
        $tests = Tests::findByExercise($id)->toArray();
        $identity = $this->auth->getIdentity();

        foreach ($tests as $key => $test) {
            if ($test['user'] != $identity['id']) {
                $user = Users::findFirstById($test['user']);
                if ($user) {
                    $tests[$key]['user'] = $user->name;
                }
            } else {
                unset($test[$key]);
            }
        }
        $this->view->tests = $tests;
        $this->view->exercise = $exercise;
    }

}
